package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.DateUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysUserService;
import com.ccp.dev.qbdms.consts.HighlightConst;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.WQbdMyCollection;
import com.ccp.dev.qbdms.model.WQbdMyKnowledge;
import com.ccp.dev.qbdms.model.WQbdMyPushRecord;
import com.ccp.dev.qbdms.model.WQbdQualityKnow;
import com.ccp.dev.qbdms.service.WQbdMyCollectionService;
import com.ccp.dev.qbdms.service.WQbdMyKnowledgeService;
import com.ccp.dev.qbdms.service.WQbdMyPushRecordService;
import com.ccp.dev.qbdms.service.WQbdQualityKnowService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.Doc2PdfUtil;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.consts.SecretUtil;
import com.ccp.dev.system.model.*;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.service.*;
import com.ccp.dev.system.util.SysRoleUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.ccp.dev.extend.util.ServiceUtil.getBasePath;
import static com.ccp.dev.qbdms.consts.ZhiLiangConst.*;

/**
 * 质量知识 信息操作处理控制器
 *
 * @author 于金
 * @date 2020-07-20 10:41:54
 */
@Controller
/**
 * 请将此名称添加到日志开关${login.mapping}
 */
@Action(customModel = "质量知识")
@RequestMapping("/qbdms/wQbdQualityKnow")
public class WQbdQualityKnowController extends SysBaseController {
    @Resource
    private WQbdQualityKnowService wQbdQualityKnowService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private GlobalTypeService globalTypeService;


    @Resource
    WQbdMyCollectionService wQbdMyCollectionService;

    @Resource
    WQbdMyPushRecordService wQbdMyPushRecordService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @Resource
    WQbdMyKnowledgeService wQbdMyKnowledgeService;

    private void setDicToModelMap(String key, ModelMap modelMap) {
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey(key, false);
        modelMap.put(key + "List", JSON.toJSONString(dicList));
    }


    /**
     * 验证当前登录人的所属部门和所属角色
     * 删改权限
     *
     * @return
     */
    public boolean checkRoleDept(String alias,String id) {
        try {
            WQbdQualityKnow wQbdQualityKnow = wQbdQualityKnowService.getOneById(id);
            String createBy = wQbdQualityKnow.getCreateBy();
            //每条数据的部门
            SysOrg createOrg = sysOrgService.getOrgByUserId(createBy);
//            if (currentRoleId.equals(wQbdQualityKnow.getRoleId())){
//                if (ContextUtil.getCurrentOrgId().equals(createOrg.getOrgId())){
//                    return  true;
//                }else{
//                    return false;
//                }
//            }
            if (alias.equals("bpm_sld")||alias.equals("bpm_zlzhzly")||alias.equals("bpm_bmld")||alias.equals("bpm_qnzl")){
                if (ContextUtil.getCurrentOrgId().equals(createOrg.getOrgId())){
                    return  true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 验证当前登录人的所属角色
     * 增加验证
     *
     * @return
     */
    public boolean checkRoleDeptAdd(SysRole currentRole) {
        try {
            if (currentRole.getAlias().equals("bpm_bmld")||currentRole.getAlias().equals("bpm_qnzl")||currentRole.getAlias().equals("bpm_zlzhzly")||currentRole.getAlias().equals("bpm_sld")){
               return  true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 条件字典显示
     */
    public ModelMap getDic(ModelMap modelMap) {
//        年度
        Map<String, Object> map = new HashMap<>();
        List listYear = new ArrayList();
        String year = DateUtil.getYeat();
        int year1 = Integer.valueOf(year) - 1;
        int year2 = Integer.valueOf(year) - 2;
        listYear.add(year);
        listYear.add(String.valueOf(year1));
        listYear.add(String.valueOf(year2));
        modelMap.put("listYear", JSON.toJSONString(listYear));
        //发布人
        List<SysUser> sysUsers = sysUserService.queryUserListByOrgId("9e8bb347c87b47c9a391bed1da02d174");
        modelMap.put("sysUsers", JSON.toJSONString(sysUsers));
        //密级
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("sjmj", false);
        JSON.toJSONString(dicList);
        modelMap.put("mj", JSON.toJSONString(dicList));
        //部门
        List<SysOrg> resultOrg = new ArrayList<SysOrg>();
        List<SysOrg> sysOrgList = sysOrgService.queryAll();
        Iterator<SysOrg> it = sysOrgList.iterator();
        while(it.hasNext()){
            SysOrg x = it.next();
            if(x.getCode().equals("1734")){
                x.setIsTenant(0);
            }
        }
//        List<SysOrg> listOrg = sysOrgService.querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("1734").getOrgId());
//        for (SysOrg org : listOrg) {
//            if (org.getCode().equals("wrj")) {
//                List<SysOrg> listOrgSub =sysOrgService
//                    .querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("wrj").getOrgId());
//                resultOrg.addAll(listOrgSub);
//            } else {
//                resultOrg.add(org);
//            }
//        }
        modelMap.put("sysOrgList", JSON.toJSONString(sysOrgList));
        return modelMap;
    }


    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到质量知识首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,ModelMap modelMap) {
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        getDic(modelMap);
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        boolean isdd=checkRoleDeptAdd(currentRole);
        modelMap.put("isadd",isdd);
        return "wQbdQualityKnow/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询质量知识", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request ) {
        String currentRoleId = SysRoleUtil.getCurrentRoleId(request);
        String alias = SysRoleUtil.getCurrentRoleAlias(request);

        QueryFilter queryFilter = new QueryFilter(request, true);
        ZhiLiangConst.addQueryFilter(queryFilter);
        queryFilter.remove("belongdeptname");
        queryFilter.addFilter("belongdeptname", BaseUtil.getCurrentTenOrgCodePath());
        //分页数据
//        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryList(queryFilter);
        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryES(queryFilter);
        String userId = ContextUtil.getCurrentUserId();
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        if (BeanUtils.isNotEmpty(pageDatas)) {
            pageDatas.forEach(wQbdQualityKnow -> {
                //密级回显
                dicList.forEach(dictionary -> {
                    if (dictionary.getItemValue().equals(wQbdQualityKnow.getSecret())) {
                        wQbdQualityKnow.setSecret(dictionary.getItemName());
                    }
                });
                String enclosure = wQbdQualityKnow.getEnclosure();
                enclosure = enclosure.substring(1, enclosure.length() - 1);
                Map<String, Object> parse = JSON.parseObject(enclosure);
                String fileId = parse.get("fileId").toString();
                wQbdQualityKnow.setFileId(fileId);
                WQbdMyCollection wQbdMyCollection = wQbdMyCollectionService.queryIsSc(userId, wQbdQualityKnow.getId());
                if (ObjectUtils.isEmpty(wQbdMyCollection)) {
                    wQbdQualityKnow.setCollectionStatus(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_NO));
                } else {
                    wQbdQualityKnow.setCollectionStatus(wQbdMyCollection.getStatus());
                }
                boolean isEdit=checkRoleDept(alias,wQbdQualityKnow.getId());
                wQbdQualityKnow.setEdit(isEdit);
            });
        }

        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }

    /**
     * 功能描述: 获取知识分类字典数据
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping("/getKnowDic")
    @ResponseBody
    @Action(description = "获取知识分类字典数据", detail = "获取知识分类字典数据<#if success>成功<#else></#if>")
    public Object getKnowDic() {
        Map<String, Object> zsfl1 = dictionaryService.getTreeDicByNodeKey("zsfl1");
        return zsfl1;
    }

    @Resource
    private SysFileService sysFileService;
    //openOffice服务地址
    @Value("${openoffice.host}")
    private String OpenOfficeHost;
    @Value("${openoffice.port}")
    //openOffice服务端口
    private Integer OpenOfficePort;

    /**
     * 功能描述: 预览pdf
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping("/showPDFFileLoad")
    @ResponseBody
    @Action(description = "预览pdf读取状态判断", detail = "预览pdf读取状态判断<#if success>成功<#else></#if>")
    public Object showPDFFileLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileId") String fileId) throws ConnectException {
        request.getParameter("fileId");
        String basePath = getBasePath();
        SysFile sysFile = sysFileService.getOneById(fileId);
        String path = basePath + File.separator + sysFile.getFilePath();
        if (!path.endsWith(".pdf")) {
            Doc2PdfUtil doc2PdfUtil = new Doc2PdfUtil(OpenOfficeHost, OpenOfficePort);
            //doc转pdf，返回pdf文件 如果存已经在pdf不转了
            File file = doc2PdfUtil.doc2Pdf(path);
//            getOutputStream(file,response);
            return success("loading结束");
        } else {
            File file = new File(path);
//            getOutputStream(file,response);
            return success("loading结束");
        }
    }


    /**
     * 功能描述: 预览pdf
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping("/showPDFFile")
    @ResponseBody
    @Action(description = "预览pdf", detail = "预览pdf<#if success>成功<#else></#if>")
    public void showPDFFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileId") String fileId) throws ConnectException {
        request.getParameter("fileId");
        String basePath = getBasePath();
        SysFile sysFile = sysFileService.getOneById(fileId);
        String fileName = sysFile.getFileName().toLowerCase();
        String path = basePath + File.separator + sysFile.getFilePath();
        if (!path.endsWith(".pdf")) {
            Doc2PdfUtil doc2PdfUtil = new Doc2PdfUtil(OpenOfficeHost, OpenOfficePort);
            //doc转pdf，返回pdf文件 如果存已经在pdf不转了
            File file = doc2PdfUtil.doc2Pdf(path);
            getOutputStream(file, response);
        } else {
            File file = new File(path);
            getOutputStream(file, response);
        }
    }

    public void getOutputStream(File file, HttpServletResponse response) {
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到质量知识新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        setDicToModelMap("zsfl1", modelMap);
        GlobalType zsfl1 = globalTypeService.getByDictNodeKey("zsfl1");
        modelMap.put("typeId", zsfl1.getTypeId());
        modelMap.put("id", id);
        String fileManagementUploadType = PropertyUtil.getByAlias("QAreportUploadType", "");
        modelMap.put("fileManagementUploadType", fileManagementUploadType);
        String wjszsdsxlx = PropertyUtil.getByAlias("wjszsdsxlx", "");
        modelMap.put("wjszsdsxlx", wjszsdsxlx);

        //可见范围
        setDicToModelMap("kjfw", modelMap);
        //是否发送推送消息
        setDicToModelMap("spfstsxx", modelMap);

        return "wQbdQualityKnow/add";
    }


    @Resource
    private ExtendSysUserService extendSysUserService;
    @Resource
    private SysOrgService sysOrgService;

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdQualityKnow 保存的对象
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存质量知识数据", detail = "<#if isAdd>新增<#else>编辑</#if>质量知识数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdQualityKnow wQbdQualityKnow, HttpServletRequest request) {
        String id = wQbdQualityKnow.getId();
        String userId = ContextUtil.getCurrentUserId();
        String visibleRange = wQbdQualityKnow.getVisibleRange();
        String pushState = wQbdQualityKnow.getPushState();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQualityKnow.setId(UUIDUtils.getUUIDFor32());
            wQbdQualityKnow.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdQualityKnow.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdQualityKnow.setCreateTime(new Date());
            wQbdQualityKnow.setUpdateTime(new Date());
            wQbdQualityKnow.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdQualityKnow.setDepartCode(ContextUtil.getCurrentOrgId());
            wQbdQualityKnow.setRoleId(SysRoleUtil.getCurrentRoleId(request));
            ZhiLiangConst.addCommonFields(wQbdQualityKnow);
            if (visibleRange.equals(HighlightConst.visibleRange) || visibleRange.equals("")) {
                wQbdQualityKnow.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath().substring(0,5));
            } else {
                wQbdQualityKnow.setBelongdeptname(BaseUtil.getCurrentOrgCode());
            }

            wQbdQualityKnow.setStatus(HAIR_DOWN_MAP.get(ZhiLiangConst.GROUP_PREPARE_SEND));
            wQbdQualityKnowService.addAndupdate(wQbdQualityKnow);
            result = wQbdQualityKnowService.add(wQbdQualityKnow);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            wQbdQualityKnow.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdQualityKnow.setUpdateTime(new Date());
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdQualityKnow);
            if (visibleRange.equals(HighlightConst.visibleRange) || visibleRange.equals("")) {
                wQbdQualityKnow.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath().substring(0,5));
            } else {
                wQbdQualityKnow.setBelongdeptname(BaseUtil.getCurrentOrgCode());
            }
            result = wQbdQualityKnowService.update(wQbdQualityKnow);
            WQbdQualityKnow qbdQualityKnow = wQbdQualityKnowService.getOneById(id);
            String modifyInfo = StructureModifyUtil.getModifyInfo(qbdQualityKnow, wQbdQualityKnow);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", modifyInfo);
            wQbdQualityKnowService.addAndupdate(qbdQualityKnow);
        }
        //查找设置感兴趣的记录表  用户进行推送
        QueryFilter queryFilter = new QueryFilter(request);
        queryFilter.addFilter("knowledge_classifica", wQbdQualityKnow.getKnowledgeClassification());
        if (pushState.equals(HighlightConst.pushState)) {
            if (visibleRange.equals(HighlightConst.visibleRange) || visibleRange.equals("")) {
                //查找全所user
                SysOrg sysOrgByOrgCode = sysOrgService.getSysOrgByOrgCode(HighlightConst.orgCode);
                List<SysUser> sysUserList = extendSysUserService.queryUsersByOrg(sysOrgByOrgCode.getPath() + "%");
                Iterator<SysUser> it=sysUserList.iterator();
                while (it.hasNext()){
                    SysUser sysUser = it.next();
                    if(SecretUtil.getUserDataSecretMap().get(sysUser.getPrivacyLevel())<Integer.parseInt(wQbdQualityKnow.getSecret())){
                        it.remove();
                    }
                }
                addPushRecord(sysUserList, wQbdQualityKnow);
            } else {
                //查找本室user
                List<SysUser> sysUserList = sysUserService.queryUserListByOrgId(ContextUtil.getCurrentOrg().getOrgId());
                Iterator<SysUser> it=sysUserList.iterator();
                while (it.hasNext()){
                    SysUser sysUser = it.next();
                    if(SecretUtil.getUserDataSecretMap().get(sysUser.getPrivacyLevel())<Integer.parseInt(wQbdQualityKnow.getSecret())){
                        it.remove();
                    }
                }
                addPushRecord(sysUserList, wQbdQualityKnow);
            }
        }


        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }


    /**
     * 推送表里存取数据
     *
     * @param sysUserList
     * @param wQbdQualityKnow
     */
    public void addPushRecord(List<SysUser> sysUserList, WQbdQualityKnow wQbdQualityKnow) {
        try {
            sysUserList.forEach(sysUser -> {
                WQbdMyPushRecord record = wQbdMyPushRecordService.findByUserIdandTzid(sysUser.getUserId(), wQbdQualityKnow.getId());
                if (BeanUtils.isNotEmpty(record)) {
                    record.setPushStatus(HighlightConst.PUSH_YES);
                    wQbdMyPushRecordService.update(record);
                } else {
                    WQbdMyPushRecord record1 = new WQbdMyPushRecord();
                    record1.setId(UUIDUtils.getUUIDFor32());
                    record1.setPushStatus(HighlightConst.PUSH_YES);
                    record1.setKnowledgeId(wQbdQualityKnow.getId());
                    record1.setKnowledgeclassId(wQbdQualityKnow.getKnowledgeClassification());
                    record1.setCreateTime(new Date());
                    record1.setCreateBy(ContextUtil.getCurrentUserId());
                    record1.setUserid(sysUser.getUserId());
                    wQbdMyPushRecordService.add(record1);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到质量知识详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) throws NoSuchFieldException {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        WQbdQualityKnow wQbdQualityKnow = wQbdQualityKnowService.getOneById(id);
        String enclosure = wQbdQualityKnow.getEnclosure();
        enclosure = enclosure.substring(1, enclosure.length() - 1);
        Map<String, Object> parse = JSON.parseObject(enclosure);
        String fileId = parse.get("fileId").toString();
        wQbdQualityKnow.setFileId(fileId);
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        dicList.forEach(dic -> {
            if (dic.getItemValue().equals(wQbdQualityKnow.getSecret())) {
                wQbdQualityKnow.setSecret(dic.getItemName());
            }
        });

        wQbdQualityKnow.getSecret();

        SysFile sysFile = sysFileService.getOneById(fileId);
        String path=sysFile.getFilePath().replaceAll("\\\\","/");
        modelMap.put("path","Document/"+path);
        modelMap.put("filename",sysFile.getFileName()+"."+sysFile.getExt());
        modelMap.put("wQbdQualityKnow", wQbdQualityKnow);
        return "wQbdQualityKnow/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询质量知识的一条数据", detail = "根据主键id查询质量知识的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQualityKnow wQbdQualityKnow = wQbdQualityKnowService.getOneById(id);
        if (null == wQbdQualityKnow) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }

        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdQualityKnow);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除质量知识数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id,HttpServletRequest request) {
        String currentRoleId = SysRoleUtil.getCurrentRoleId(request);
        String alias = SysRoleUtil.getCurrentRoleAlias(request);
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            boolean b = checkRoleDept(alias, key);
            if (!b){
                return fail("删除失败！只能删除本部门的数据！");
            }
        }
        String[] split = id.split(",");
        //es删除
        for (String s : split) {
            wQbdQualityKnowService.delete(s);
        }
        int result = wQbdQualityKnowService.delByIdArray(split);
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success")
                : getResultDataError("delete.failure");


    }


    /**
     * 功能描述:质量知识下发
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @PostMapping("/xf")
    @ResponseBody
    @Action(description = "质量知识下发", exectype = "质量知识下发", detail = "质量知识下发<#if success>成功<#else>失败</#if>")
    public Object xf(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("下发失败，未传入数据唯一标识!");
        }
        String[] ids = id.split(",");
        List<WQbdQualityKnow> list = new ArrayList<>();
        for (String xfid : ids) {
            WQbdQualityKnow qualityKnow = wQbdQualityKnowService.getOneById(xfid);
            //质量案例为预制字段
            Dictionary one = dictionaryService.getOneById(qualityKnow.getKnowledgeClassification());
            if (!one.getItemName().equals("质量案例")) {
                return fail("下发失败，知识分类1必须为质量案例!");
            }
            if (qualityKnow.getStatus().equals(HAIR_DOWN_MAP.get(GROUP_LOADING_SEND))) {
                return fail("下发失败,当前数据存在正在下发中的!");
            }
//            if (qualityKnow.getStatus().equals(HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3))) {
//                return fail("下发失败，当前数据中存在已经下发的!");
//            }
            list.add(qualityKnow);
        }
        //接口没有异常 正常运行程序
        //下发中状态更新
        wQbdQualityKnowService.updateList(list, HAIR_DOWN_MAP.get(GROUP_LOADING_SEND));
        //调用下发到院级单位数据接口
        boolean isSuccess = wQbdQualityKnowService.reportSend(list);
        if (isSuccess) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return isSuccess ? success("下发成功") : success("下发失败");
    }


    /**
     * 功能描述:知识收藏
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @PostMapping("/sc")
    @ResponseBody
    @Action(description = "知识收藏", exectype = "知识收藏", detail = "知识收藏<#if success>成功<#else>失败</#if>")
    public Object sc(@RequestParam("qualityknowledgeid") String qualityknowledgeid, @RequestParam("status") String status) {
        int result = 0;
        WQbdMyCollection qbdMyCollection = wQbdMyCollectionService.queryIsSc(ContextUtil.getCurrentUserId(), qualityknowledgeid);
        if (BeanUtils.isNotEmpty(qbdMyCollection)) {
            Date updateTime = new Date();
            result = wQbdMyCollectionService.updateByUserIdAndTzId(ContextUtil.getCurrentUserId(), qualityknowledgeid, HighlightConst.COLLECTION__MAP.get(status), updateTime);
        } else {
            WQbdMyCollection wQbdMyCollection = new WQbdMyCollection();
            wQbdMyCollection.setId(UUIDUtils.getUUIDFor32());
            wQbdMyCollection.setCreateTime(new Date());
            wQbdMyCollection.setQualityknowledgeid(qualityknowledgeid);
            wQbdMyCollection.setUserid(ContextUtil.getCurrentUserId());
            wQbdMyCollection.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdMyCollection.setUpdateTime(new Date());
            wQbdMyCollection.setStatus(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_YES));
            result = wQbdMyCollectionService.add(wQbdMyCollection);
        }
        return result > 0 ? success("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到质量知识导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQualityKnow/import";
    }

    /**
     * 功能描述: 导出质量知识数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping("/exportData")
    @Action(description = "导出质量知识数据信息", detail = "导出质量知识数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        if (BeanUtils.isNotEmpty(id) && id.length != 0) {
            queryFilter.put("byId", true);
            queryFilter.put("id", id);
        } else {
            queryFilter.put("byId", false);
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        Excel excel = new Excel();
        String fileName = "WQbdQualityKnow";//导出的文件名称
        excel.sheet().sheetName("sheet");// 重命名当前处于工作状态的表的名称
        List<String> titleList = new ArrayList<>();
        titleList.add("主键");
        titleList.add("知识名称");
        titleList.add("知识分类1");
        titleList.add("知识分类2");
        titleList.add("关键词");
        titleList.add("文件摘要");
        titleList.add("附件");
        titleList.add("belongdeptname");
        titleList.add("status");
        titleList.add("report_status");
        titleList.add("report_status_str");
        titleList.add("report_status_temp");
        titleList.add("secret");
        titleList.add("fillman");
        titleList.add("fillmanaccount");
        titleList.add("filldept");
        titleList.add("filldeptid");
        titleList.add("filldate");
        titleList.add("filldept_hospital");
        titleList.add("租户Id");
        titleList.add("创建人");
        titleList.add("创建时间");
        titleList.add("更新人");
        titleList.add("更新时间");
        titleList.add("密级");
        excel.row(0, 0).value(titleList.toArray());
        excel.row(0, 0).font(new IFontEditor() {
            // 设置字体
            @Override
            public void updateFont(Font font) {
                font.boldweight(BoldWeight.BOLD);// 粗体
            }
        }).bgColor(Color.GREY_25_PERCENT).width(3500);
        excel.row(0, 1).width(3500);
        excel.row(0, 2).width(3500);
        excel.row(0, 3).width(3500);
        excel.row(0, 4).width(3500);
        //设置列的数据格式
        excel.sheet().setDefaultColumnStyle(0, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(1, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(2, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(3, DataFormat.TEXT);
        ExcelUtil.downloadExcel(wQbdQualityKnowService.exportExcel(excel, queryFilter), fileName, response);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdQualityKnow> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdQualityKnow dataToInsert = new WQbdQualityKnow();
                int i = 0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                    //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdQualityKnowService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
    }


}
